import 'package:collection/collection.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/models/cart_add.dart';
import 'package:fsharing/core/models/product_detail.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/pages/store/product_detail_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';

/// 加入购物车
class CartAddModel extends ViewModel {
  final Api api;
  final ProductDetail productDetail;
  final Map<String, int> currentSku;
  int _quantity = 1;
  CartAdd _data;
  String _errorMessage;

  CartAddModel(this.api, ProductDetailModel model)
      : productDetail = model.productDetail,
        currentSku = {}..addAll(model.productDetail.currentSku),
        super();

  int get quantity => _quantity;

  set quantity(int value) {
    _quantity = value;
    notifyListeners();
  }

  CartAdd get data => _data;
  String get errorMessage => _errorMessage;

  /// 获取当前Sku
  Sku querySku() {
    return productDetail.skus.firstWhere(
      (element) => MapEquality().equals(element.sku, currentSku),
      orElse: () => productDetail.skus.firstWhere(
        (element) =>
            MapEquality().equals(element.sku, productDetail.currentSku),
      ),
    );
  }

  /// 获取当前Mia
  Mia queryMia() {
    // 根据currentSku查询miaId
    var sku = querySku();
    // 查询有没有Mia
    return productDetail.allMia.firstWhere(
      (element) => element.id == sku.miaId,
      orElse: () => productDetail.defaultMia,
    );
  }

  /// 判断可选与否
  bool selectable(Option option, OptionValue optionValue) {
    for (Sku sku in productDetail.skus) {
      var currentSkuTemp = {}..addAll(currentSku);
      currentSkuTemp[option.id.toString()] = optionValue.id;
      var isSub = currentSkuTemp.entries.every(
        (mapEntry) => DeepCollectionEquality()
            .equals(mapEntry.value, sku.sku[mapEntry.key]),
      );
      if (isSub) {
        return true;
      }
    }
    return false;
  }

  /// 获取是否选择
  bool selected(Option option, OptionValue optionValue) {
    var mapEntry = currentSku.entries.firstWhere(
      (element) =>
          element.key == option.id.toString() &&
          element.value == optionValue.id,
      orElse: () => null,
    );
    return mapEntry != null;
  }

  /// 切换选择
  void toggle(Option option, OptionValue optionValue) {
    var mapEntry = currentSku.entries.firstWhere(
      (element) =>
          element.key == option.id.toString() &&
          element.value == optionValue.id,
      orElse: () => null,
    );
    if (mapEntry == null) {
      currentSku[option.id.toString()] = optionValue.id;
    } else {
      currentSku.remove(option.id.toString());
    }
    notifyListeners();
  }

  /// 加入购物车
  Future<ViewState> cartAdd() async {
    viewState = ViewState.busy;
    try {
      var mia = queryMia();
      debugPrint('mia = ${mia.toJson()}, quantity = $quantity');
      _data = await api.cartAdd(mia.id, quantity, productDetail.referStoreId);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
